#!/usr/bin/env python3
"""
Model Evaluator API 使用示例

这个脚本展示了如何直接调用后端API进行图像查询
"""

import requests
import json

def test_image_query():
    """测试图像查询API"""
    
    # API端点
    url = "http://localhost:8000/api/image-query"
    
    # 请求数据
    data = {
        "image_url": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg",
        "query": "这是什么？"
    }
    
    try:
        print("正在调用API...")
        print(f"图片URL: {data['image_url']}")
        print(f"查询问题: {data['query']}")
        print("-" * 50)
        
        # 发送POST请求
        response = requests.post(url, json=data)
        
        # 检查响应状态
        if response.status_code == 200:
            result = response.json()
            
            if result['success']:
                print("✅ API调用成功!")
                print("返回结果:")
                print(json.dumps(json.loads(result['result']), indent=2, ensure_ascii=False))
            else:
                print("❌ API调用失败:")
                print(f"错误信息: {result['error']}")
        else:
            print(f"❌ HTTP错误: {response.status_code}")
            print(f"响应内容: {response.text}")
            
    except requests.exceptions.ConnectionError:
        print("❌ 连接错误: 请确保后端服务正在运行 (http://localhost:8000)")
    except Exception as e:
        print(f"❌ 未知错误: {str(e)}")

def test_api_health():
    """测试API健康状态"""
    try:
        response = requests.get("http://localhost:8000/")
        if response.status_code == 200:
            print("✅ 后端服务运行正常")
            return True
        else:
            print("❌ 后端服务响应异常")
            return False
    except requests.exceptions.ConnectionError:
        print("❌ 无法连接到后端服务")
        return False

if __name__ == "__main__":
    print("Model Evaluator API 测试")
    print("=" * 50)
    
    # 首先测试服务是否运行
    if test_api_health():
        print("\n开始测试图像查询功能...")
        test_image_query()
    else:
        print("\n请先启动后端服务:")
        print("1. 设置环境变量: export DASHSCOPE_API_KEY='your-api-key'")
        print("2. 运行: ./start_backend.sh")
        print("3. 或者: cd backend && python main.py") 